

package com.bei_en.teacher.management.controller.questions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionStatus;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bei_en.common.ExcelUtilController;
import com.bei_en.common.util.tencent.UploadUtil;
import com.bei_en.common.web.JsonFailResult;
import com.bei_en.common.web.JsonResult;
import com.bei_en.common.web.JsonSuccessResult;
import com.bei_en.teacher.admin.model.education.condition.EducationCondition;
import com.bei_en.teacher.admin.model.education.vo.EducationVo;
import com.bei_en.teacher.admin.model.questions.condition.QuestionsTypeCondition;
import com.bei_en.teacher.admin.model.questions.vo.QuestionsTypeVo;
import com.bei_en.teacher.admin.model.questions.vo.QuestionsVo;
import com.bei_en.teacher.admin.model.regions.condition.RegionsCondition;
import com.bei_en.teacher.admin.model.regions.vo.RegionsVo;
import com.bei_en.teacher.admin.model.subject.condition.SubjectCondition;
import com.bei_en.teacher.admin.model.subject.vo.SubjectVo;
import com.bei_en.teacher.admin.service.education.EducationService;
import com.bei_en.teacher.admin.service.questions.QuestionsTypeService;
import com.bei_en.teacher.admin.service.regions.RegionsService;
import com.bei_en.teacher.admin.service.subject.SubjectService;
import com.bei_en.teacher.management.controller.BaseController;
import com.bei_en.teacher.management.web.MyJsonFailResult;
import com.bei_en.teacher.management.web.MyJsonResult;
import com.bei_en.teacher.management.web.MyJsonSuccessResult;

/**
 * 
 * @author Guocg
 * @date 2016-8-18 9:18:37
 */
@Controller
@RequestMapping("/admin")
public class QuestionsTypeController extends BaseController {
	   @Autowired
	    RegionsService regionsService;
	   @Autowired
	    SubjectService subjectService;
	   @Autowired
	    EducationService educationService;
    @Autowired
    QuestionsTypeService questionsTypeService;
    private Map<String, String> uploadMap = new ConcurrentHashMap<String, String>();// no
    private void addSharedAttr(Model model) {
    	model.addAttribute("Type", gson.fromJson("{1:'题',2:'真题'}", Map.class));
    }
    @RequestMapping("/questionsType")
    public String questionsType(Model model,QuestionsTypeCondition vo, HttpServletResponse resp ) {

		List<QuestionsTypeVo> list =new ArrayList<QuestionsTypeVo>();
		try {
		    list = questionsTypeService.findQuestionsTypePage(vo);
		} catch (Exception e) {
		    e.printStackTrace();
		    writeJson(resp, new MyJsonFailResult(e.getMessage()));
		    return null;
		}
	
		model.addAttribute("list", list);
		model.addAttribute("Education", getListEducation());
		model.addAttribute("Subject", getListSubject());
		model.addAttribute("Province", getProvince());
		model.addAttribute("City", getCity());
		model.addAttribute("Area", getArea());
		addSharedAttr(model);
		model.addAttribute("vo", vo);
	
		return "/admin/questions/typeList.html";
    }

    @RequestMapping("/questionsTypeAdd")
    public String questionsTypeAdd(Model model, QuestionsTypeVo vo, boolean show, HttpSession session,
	    HttpServletResponse resp) {

	if (show) {
	    addSharedAttr(model);
//		List<RegionsVo> list =new ArrayList<RegionsVo>();
//		RegionsCondition regionvo=new RegionsCondition();
//		regionvo.setPageSize(Integer.MAX_VALUE);
//		regionvo.setQueryWhere("province_id=0&city_id=0&area_id=0");
//		   list = regionsService.findRegionsPage(regionvo);
//		   JSONObject object=null;
//		   JSONArray array=new JSONArray();
//		   for (int i = 0; i < list.size(); i++) {
//			   object=new JSONObject();
//			   object.accumulate("value", list.get(i).getItemId());
//			   object.accumulate("lable", list.get(i).getItemName());
//			   array.add(object);
//		}
//		model.addAttribute("regionsProvince", array);
	    model.addAttribute("Education", getListEducation())	    ;
	    model.addAttribute("Subject", getListSubject())	    ;
//		List<SubjectVo> subjectVos=	subjectService.findAll();
//		JSONArray   array2=new JSONArray();
//		for (int i = 0; i < subjectVos.size(); i++) {
//			  object=new JSONObject();
//			  subjectVos.get(i).getName();
//			  
//			  array2.add(object);
//		}
	    return "/admin/questions/typeAdd.html";
	}
	try {
	   /* SysUserVo obj = getLoginUser(session);
	    if (obj!=null)
		vo.setCreateId(obj.getId());
	    else
		vo.setCreateId(0);*/
	    vo.setCreateTime(new Date());
	    vo.setMakeFraction(0d);
	    vo.setMakeTime(0);
	    vo.setFractionSum(0l);
	    vo.setWeight(0d);
	    vo.setStudyNum(0);
	    vo.setQuestionsSum(0l);
	    vo.setYesNum(0);
	    vo.setMakeNum(0);
	    vo.setType(1);
	    if(vo.getEducationId()==-1){
	    	vo.setEducationId(null);
	    }else{
	    	EducationVo educationVo=	educationService.findById(vo.getEducationId());
	       	vo.setProvinceId(educationVo.getProvinceId());
	    	vo.setAreaId(educationVo.getAreaId());
	    	vo.setCityId(educationVo.getCityId());
	    }
	    if(vo.getSubjectId()==-1){
	    	vo.setSubjectId(null);
	    }else{
	    	SubjectVo educationVo=	subjectService.findById(vo.getSubjectId());
	    	vo.setProvinceId(educationVo.getProvinceId());
	    	vo.setAreaId(educationVo.getAreaId());
	    	vo.setCityId(educationVo.getCityId());
	    }
	    
	    if((vo.getSubjectId()==null&&vo.getEducationId()==null)||((vo.getSubjectId()!=null&&vo.getSubjectId()==-1)&&(vo.getEducationId()!=null&&vo.getEducationId()==-1))){
	    	   writeJson(resp, new MyJsonFailResult("报考学科和教育综合必选一个"));
	   	    return null;
	    }
	questionsTypeService.insert(vo);
	} catch (Exception e) {
	    e.printStackTrace();
	    writeJson(resp, new MyJsonFailResult(e.getMessage()));
	    return null;
	}
	MyJsonSuccessResult re = new MyJsonSuccessResult();
	re.setCloseCurrent(true);
	re.setTabid("questionsTypeList");
	writeJson(resp, re);
	return null;
    }

    @RequestMapping("/questionsTypeEdit")
    public String questionsTypeEdit(Model model,boolean show, QuestionsTypeVo vo, HttpSession session, HttpServletResponse resp) {
	
		if (show) {
		    QuestionsTypeVo vo1 = questionsTypeService.findById(vo.getId());
		    addSharedAttr(model);
			List<RegionsVo> list =new ArrayList<RegionsVo>();
			RegionsCondition regionvo=new RegionsCondition();
			regionvo.setPageSize(Integer.MAX_VALUE);
			regionvo.setQueryWhere("province_id=0&city_id=0&area_id=0");
			   list = regionsService.findRegionsPage(regionvo);
			   JSONObject object=null;
			   JSONArray array=new JSONArray();
			   for (int i = 0; i < list.size(); i++) {
				   object=new JSONObject();
				   object.accumulate("value", list.get(i).getItemId());
				   object.accumulate("lable", list.get(i).getItemName());
				   array.add(object);
			}
			model.addAttribute("regionsProvince", array);
			
			RegionsCondition regionsCondition=new RegionsCondition();
			regionsCondition.setProvinceId(vo1.getProvinceId());
			regionsCondition.setAreaId(0);
			model.addAttribute("getRegionsCity", getRegionsCity(regionsCondition));
			
			regionsCondition=new RegionsCondition();
			regionsCondition.setCityId(vo1.getCityId());
			model.addAttribute("getRegionsArea", getRegionsArea(regionsCondition));
		    
			SubjectCondition subjectCondition=new SubjectCondition();
			subjectCondition.setEducationId(vo1.getEducationId());
			model.addAttribute("getSubjectType", getSubjectType(subjectCondition));	
			
			EducationCondition educationCondition=new EducationCondition();
			educationCondition.setCityId(vo1.getCityId());
			educationCondition.setProvinceId(vo1.getProvinceId());
			educationCondition.setAreaId(vo1.getAreaId());
			model.addAttribute("getEducationType", getEducationType(educationCondition));	
		    model.addAttribute("vo", vo1);
		    return "/admin/questions/typeEdit.html";
		}
		try {
		   /* SysUserVo obj = getLoginUser(session);
		    if (obj!=null)
			vo.setUpdateId(obj.getId());
		    else
			vo.setUpdateId(0);*/
//		    vo.setUpdateTime(new Date());
			
			   if(vo.getEducationId()==-1){
			    	vo.setEducationId(0);
			    }else{
			    	EducationVo educationVo=	educationService.findById(vo.getEducationId());
			       	vo.setProvinceId(educationVo.getProvinceId());
			    	vo.setAreaId(educationVo.getAreaId());
			    	vo.setCityId(educationVo.getCityId());
			    }
			    if(vo.getSubjectId()==-1){
			    	vo.setSubjectId(0);
			    }else{
			    	SubjectVo educationVo=	subjectService.findById(vo.getSubjectId());
			    	vo.setProvinceId(educationVo.getProvinceId());
			    	vo.setAreaId(educationVo.getAreaId());
			    	vo.setCityId(educationVo.getCityId());
			    }
		questionsTypeService.updateSelective(vo);
		} catch (Exception e) {
		    e.printStackTrace();
		    writeJson(resp, new MyJsonFailResult(e.getMessage()));
		    return null;
		}
		MyJsonSuccessResult re = new MyJsonSuccessResult();
		re.setCloseCurrent(true);
		re.setTabid("questionsTypeList");
		writeJson(resp, re);
		return null;
    }

    @RequestMapping("/questionsTypeDel")
    @ResponseBody
    public MyJsonResult questionsTypeDel(Model model, int[] delids, HttpSession session) {

		try {
		    for (int i : delids) {
			QuestionsTypeVo vo1 = new QuestionsTypeVo();
			vo1.setId(i);
//			vo1.setStatus(0);
			/*SysUserVo obj = getLoginUser(session);
			if (obj!=null)
			    vo1.setUpdateId(obj.getId());
			else
			    vo1.setUpdateId(0);*/
//			vo1.setUpdateTime(new Date());
			questionsTypeService.delete(i);;
		    }
		} catch (Exception e) {
		    e.printStackTrace();
		    return new MyJsonFailResult(e.getMessage());
		}
		return new MyJsonSuccessResult();
	}
    @RequestMapping("/regionsProvince")
   	@ResponseBody
       public JSONArray regionsProvince(Model model,RegionsCondition vo, BindingResult br, HttpSession session) {

   		List<RegionsVo> list =new ArrayList<RegionsVo>();
   		vo.setPageSize(Integer.MAX_VALUE);
   		   list = regionsService.findRegionsPage(vo);
   		   JSONObject object=null;
   		   JSONArray array=new JSONArray();
   		 switch ( vo.getProvinceId()) {
   	   case 0:
				   for (int i = 0; i < list.size(); i++) {
	      			   object=new JSONObject();
	      			   object.accumulate("value", list.get(i).getCityId());
	      			  object.accumulate("label", list.get(i).getItemName());
	      			   array.add(object);
	      		}
				break;
			default:
				  object=new JSONObject();
				   object.accumulate("label","统考");
				   object.accumulate("value", list.get(0).getCityId());
				   array.add(object);
				break;
			}
   
   		return array;
       }
       @RequestMapping("/regionsArea")
   	@ResponseBody
       public JSONArray regionsArea(Model model,RegionsCondition vo, BindingResult br, HttpSession session) {
   		return getRegionsArea(vo);
       }
       @RequestMapping("/regionsCity")
   	@ResponseBody
       public JSONArray regionsCity(Model model,RegionsCondition vo, BindingResult br, HttpSession session) {
   		return getRegionsCity(vo);
       }
       
       @RequestMapping("/educationType")
   		@ResponseBody
       public JSONArray educationType(Model model,EducationCondition vo, HttpServletResponse resp ) {
		return getEducationType(vo);
       }
       @RequestMapping("/subjectType")
    	@ResponseBody
       public JSONArray subjectType(Model model,SubjectCondition vo, HttpServletResponse resp ) {
   		return getSubjectType(vo);
       }
       public JSONArray getSubjectType(SubjectCondition vo){
    	   List<SubjectVo> list =new ArrayList<SubjectVo>();
    	   SubjectCondition condition=new SubjectCondition();
    	   condition.setPageSize(Integer.MAX_VALUE);
    	   condition.setParent(0);
     		list = subjectService.findSubjectPage(condition);
     		  JSONObject object=null;
    		   JSONArray array=new JSONArray();
    		   for (int i = 0; i < list.size(); i++) {
    			   object=new JSONObject();
    			   object.accumulate("value", list.get(i).getId());
    			   object.accumulate("label", list.get(i).getName());
    			   array.add(object);
    			   condition=new SubjectCondition();
    			   condition.setParent(list.get(i).getId());
    			 List<SubjectVo>		 item = subjectService.findSubjectPage(condition);
    			   for (int j = 0; j < item.size(); j++) {
    				 object=new JSONObject();
      			   object.accumulate("value", item.get(j).getId());
      			   object.accumulate("label","&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+ item.get(j).getName());
      			   array.add(object);
  			}
    		}
     		return array;
       }
  public JSONArray getEducationType(EducationCondition vo){
	  List<EducationVo> list =new ArrayList<EducationVo>();
//	  EducationCondition educationCondition=new EducationCondition();
//	  educationCondition.setPageSize(Integer.MAX_VALUE);
//	  educationCondition.setParent(0);
//		  list = educationService.findEducationPage(educationCondition);
		  list = educationService.findAll();
	  JSONObject object=null;
	   JSONArray array=new JSONArray();
	   for (int i = 0; i < list.size(); i++) {
		   object=new JSONObject();
		   
		   object.accumulate("value", list.get(i).getId());
//		   object.accumulate("label", regionsService.findById(list.get(i).getProvinceId()).getItemName()+"--"+list.get(i).getName());
		   object.accumulate("label", list.get(i).getName());
		   array.add(object);
	}
	return array;
       }
    

  @RequestMapping("/questionsTypeDialog")
  public String userInvoiceDialog(Model model, QuestionsVo vo, HttpSession session,
	    HttpServletResponse resp) {

	return "/admin/questions/questionsTypeDialog.html";
  }

  @RequestMapping(value = "/realestate/uploadExcel2", method = RequestMethod.POST)
  @ResponseBody
  public JsonResult uploadFile(Model model, MultipartFile file, String base, HttpSession session) {
	Map map = new HashMap();
	String picUrl = null;
	try {
	    picUrl = UploadUtil.uploadLocal(request, file);
	    if (picUrl!=null) {
	    	ExcelUtilController excelUtil=new ExcelUtilController();
		Map map1 =excelUtil .realestateImportExcel2(picUrl, true);
		map.put("total", map1.get("total"));
		map.put("right", map1.get("right"));
		map.put("wrong", map1.get("wrong"));
		map.put("base", base);
		uploadMap.put(session.getId(), picUrl);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    return new JsonFailResult(session.getId());
	}
	return new JsonSuccessResult(session.getId(), map);
  }

  @RequestMapping(value = "/realestate/importExcel2", method = RequestMethod.POST)
  @ResponseBody
  public Object importExcel(Model model, HttpSession session) {

	Map map = new HashMap();

	String picUrl = uploadMap.get(session.getId());
	log.info("excelUrl="+picUrl);
//	picUrl = "D:/amIurs/git/smart-yuda-java/SmartYuda/WebRoot/upload/a2f46418f5074890810c86a699489b23.xls";

	if (picUrl==null) {
	    map.put("statusCode", 300);
	    map.put("message", "文件丢失");
	    return map;
	}

	Map map1;
	try {
		ExcelUtilController excelUtil=new ExcelUtilController();
	    map1 = excelUtil.realestateImportExcel2(picUrl, false);
	} catch (Exception e1) {
	    e1.printStackTrace();
	    map.put("statusCode", 300);
	    map.put("message", e1.getMessage());
	    return map;
	}
	List<QuestionsTypeVo> list = (List<QuestionsTypeVo>) map1.get("list");
	int count = 0;
//	List<CommunityRealestateExcelImport> wrongList = new ArrayList<CommunityRealestateExcelImport>();
	TransactionStatus transactionStatus=	questionsTypeService.getTransactionStatus();
	try {
		for (QuestionsTypeVo vo : list) {
			
			if(vo.getSubjectName()!=null){
				 SubjectCondition  subjectCondition=new SubjectCondition();
				    subjectCondition.setName(vo.getSubjectName().trim());
				    List<SubjectVo> subjectVos=   subjectService.findSubjectPage(subjectCondition);
				    if(!subjectVos.isEmpty()){
				    	vo.setSubjectId(subjectVos.get(0).getId());
				    	vo.setAreaId(subjectVos.get(0).getAreaId());
				    	vo.setCityId(subjectVos.get(0).getCityId());
				    	vo.setProvinceId(subjectVos.get(0).getProvinceId());
				    }
			}
			if(vo.getEducationName()!=null){
		        EducationCondition  educationCondition=new EducationCondition();
		    	educationCondition.setName(vo.getEducationName().trim());
			    List<EducationVo> educationVos=   educationService.findEducationPage(educationCondition);
			    if(!educationVos.isEmpty()){
			    	vo.setEducationId(educationVos.get(0).getId());
			    	vo.setAreaId(educationVos.get(0).getAreaId());
			    	vo.setCityId(educationVos.get(0).getCityId());
			    	vo.setProvinceId(educationVos.get(0).getProvinceId());
			    }
			}
	       
			questionsTypeService.insert(vo);
			count++;
		}
		questionsTypeService.commit(transactionStatus);
	} catch (Exception e) {
		questionsTypeService.rollback(transactionStatus);
	}

	map.put("statusCode", 200);
	map.put("closeCurrent", true);
	map.put("tabid", "communityRealestateList");
	map.put("right", count);
//	map.put("wrong", wrongList);
	uploadMap.remove(session.getId());

	return map;
  }
       
}
